import requests
import mysql.connector
from mysql.connector import Error
import json
import os
import sys
from datetime import datetime
import argparse

def load_config(config_path):
    try:
        with open(config_path, 'r', encoding='utf-8') as f:
            return json.load(f)
    except FileNotFoundError:
        print(f"Configuration file {config_path} not found!")
        sys.exit(1)
    except json.JSONDecodeError:
        print(f"Invalid JSON in configuration file {config_path}!")
        sys.exit(1)

def connect_to_db():
    try:
        connection = mysql.connector.connect(
            host='localhost',
            port=3307,
            database='gitlog',
            user='gitlog_admin',
            password='gitlog_admin'
        )
        if connection.is_connected():
            print("Database connection successful!")
            return connection
    except Error as e:
        print(f"Database connection failed: {e}")
        return None

def get_gitlab_branches(base_url, token, repo_id):
    headers = {'PRIVATE-TOKEN': token}
    branches_url = f'{base_url}/projects/{repo_id}/repository/branches'
    params = {'per_page': 100}
    branches = []
    page = 1
    while True:
        params['page'] = page
        response = requests.get(branches_url, headers=headers, params=params)
        if response.status_code != 200:
            raise Exception(f"Failed to fetch branches: {response.status_code} - {response.text}")
        data = response.json()
        if not data:
            break
        branches.extend([branch['name'] for branch in data])
        page += 1
    print(f"Fetched {len(branches)} branches for repo {repo_id}.")
    return branches

def get_gitlab_commits(base_url, token, repo_id, ref_name=None, start_date=None, end_date=None):
    headers = {'PRIVATE-TOKEN': token}
    commits_url = f'{base_url}/projects/{repo_id}/repository/commits'
    params = {'per_page': 100, 'with_stats': 'true'}
    if ref_name:
        params['ref_name'] = ref_name
    if start_date:
        params['since'] = start_date
    if end_date:
        params['until'] = end_date
    commits = []
    page = 1
    while True:
        params['page'] = page
        response = requests.get(commits_url, headers=headers, params=params)
        if response.status_code != 200:
            raise Exception(f"Failed to fetch commits: {response.status_code} - {response.text}")
        data = response.json()
        if not data:
            break
        commits.extend(data)
        page += 1
    print(f"Fetched {len(commits)} commits from API for repo {repo_id} on branch '{ref_name or 'all'}'.")
    return commits  # Return full commits list to allow SHA collection

def get_db_commit_count(connection, repo_id, gitlab_instance):
    cursor = connection.cursor()
    query = """
    SELECT COUNT(*) FROM commit_log
    WHERE repository_id = %s AND gitlab_instance = %s
    """
    cursor.execute(query, (repo_id, gitlab_instance))
    result = cursor.fetchone()
    cursor.close()
    return result[0] if result else 0

def main():
    parser = argparse.ArgumentParser(description='Debug GitLab commits import')
    parser.add_argument('--repo_id', required=True, type=int, help='Repository ID to debug')
    parser.add_argument('--start_date', help='Start date (YYYY-MM-DD)')
    parser.add_argument('--end_date', help='End date (YYYY-MM-DD)')
    parser.add_argument('--gitlab_instance', default='beijing', help='GitLab instance identifier')
    args = parser.parse_args()
    
    script_dir = os.path.dirname(os.path.abspath(__file__))
    config_path = os.path.join(script_dir, 'config.json')
    config = load_config(config_path)
    env_name = 'jwzh'
    if env_name not in config:
        print(f"Environment '{env_name}' not found!")
        sys.exit(1)
    env_config = config[env_name]
    base_url = env_config['url']
    token = env_config['token']
    
    connection = connect_to_db()
    if not connection:
        sys.exit(1)
    
    try:
        branches = get_gitlab_branches(base_url, token, args.repo_id)
        print("\nBranches for repo {args.repo_id}:")
        for branch in branches:
            print(f"- {branch}")
        
        all_commits_sha = set()
        for branch in branches:
            commits = get_gitlab_commits(base_url, token, args.repo_id, ref_name=branch, start_date=args.start_date, end_date=args.end_date)
            branch_shas = {commit['id'] for commit in commits}
            print(f"Commits on branch '{branch}': {len(commits)} (unique in this fetch: {len(branch_shas)})")
            all_commits_sha.update(branch_shas)
        
        api_total_unique = len(all_commits_sha)
        db_count = get_db_commit_count(connection, args.repo_id, args.gitlab_instance)
        
        print(f"\nDebug results for repo {args.repo_id}:")
        print(f"Total unique commits across all branches from API: {api_total_unique}")
        print(f"Commits in database: {db_count}")
        if api_total_unique != db_count:
            print("Mismatch detected! Possible bug in import script.")
        else:
            print("Counts match.")
    finally:
        if connection:
            connection.close()

if __name__ == "__main__":
    main() 